import { injectable } from "inversify";
import passport from "passport";
import jsonwebtoken from "jsonwebtoken";
import { Strategy, ExtractJwt } from 'passport-jwt';

/**
 * ## 鉴权模块
 * - @param {string} secret 密钥
 * - @param {object} jwtOpiotns 配置项
 */
@injectable()
export class JWT {
  private secret: string = 'you key';
  private jwtOpiotns = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: this.secret
  }
  constructor() {
    this.strategy()
  }

  strategy() {
    let str = new Strategy(this.jwtOpiotns, (payload, done) => {
      done(null, payload);
    })

    passport.use(str);
  }

  /**
   * ### 中间件
   * - 验证接口是否登录
   * - 在请求装饰器中调用，如：@get('/login', JWT.middleware())
   */
  static middleware() {
    return passport.authenticate('jwt', { session: false });
  }

  /** 生成 token */
  public createToken(userInfo: object) {
    return jsonwebtoken.sign(userInfo, this.secret, { expiresIn: '30d' });
  }

  /** 关联 express */
  public init() {
    return passport.initialize();
  }
}